import { useState, useMemo } from 'react';
import { ImageWithLoading } from '../components/ImageWithLoading';
import { ArrowRight, Star, ChevronLeft, ChevronRight, Filter, X } from 'lucide-react';
import { usePageTitle, PAGE_TITLES } from '../lib/usePageTitle';
// Reviews data
const allReviews = [
  {
    id: 1,
    title: "TheraGun Pro: The Ultimate Recovery Tool?",
    description: "We tested the TheraGun Pro for 3 months to see if it lives up to the hype. Here's our verdict.",
    rating: 4.8,
    stars: 5,
    image: "https://images.unsplash.com/photo-1593164842264-854604db2260?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "TheraGun Pro",
    link: "/reviews/theragun-pro",
    category: "Massage Guns",
    priceRange: "Premium"
  },
  {
    id: 2,
    title: "Jarvis Standing Desk: Worth The Investment?",
    description: "After 6 months of daily use, we break down the pros and cons of this popular standing desk.",
    rating: 4.0,
    stars: 4,
    image: "https://images.unsplash.com/photo-1595846519845-68e298c2edd8?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "Jarvis Standing Desk",
    link: "/reviews/jarvis-standing-desk",
    category: "Office Equipment",
    priceRange: "Premium"
  },
  {
    id: 3,
    title: "Oura Ring Gen 3: Sleep Tracking Perfected",
    description: "Is this tiny ring the best sleep tracker on the market? Our in-depth analysis after 90 nights.",
    rating: 4.5,
    stars: 5,
    image: "https://images.unsplash.com/photo-1600861194942-f883de0dfe96?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "Oura Ring",
    link: "/reviews/oura-ring-gen-3",
    category: "Wearables",
    priceRange: "Mid-Range"
  },
  {
    id: 4,
    title: "Ekrin B37: The Best Mid-Range Massage Gun",
    description: "We put this popular massage gun through rigorous testing to see if it delivers on its promises.",
    rating: 4.5,
    stars: 5,
    image: "https://images.unsplash.com/photo-1616279969856-759f316a5ac1?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "Ekrin B37",
    link: "/reviews/ekrin-b37",
    category: "Massage Guns",
    priceRange: "Mid-Range"
  },
  {
    id: 5,
    title: "Hypervolt 2 Pro: The Quietest Premium Massage Gun",
    description: "Is the Hypervolt 2 Pro's whisper-quiet operation worth the premium price tag?",
    rating: 4.0,
    stars: 4,
    image: "https://images.unsplash.com/photo-1594737625785-a6cbdabd333c?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "Hypervolt 2 Pro",
    link: "/reviews/hypervolt-2-pro",
    category: "Massage Guns",
    priceRange: "Premium"
  },
  {
    id: 6,
    title: "Renpho Mini: The Ultra-Portable Massage Gun",
    description: "Can this tiny massage gun deliver effective recovery on the go? Our travel testing reveals all.",
    rating: 3.2,
    stars: 3,
    image: "https://images.unsplash.com/photo-1588286840104-8957b019727f?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    alt: "Renpho Mini",
    link: "/reviews/renpho-mini",
    category: "Massage Guns",
    priceRange: "Budget"
  },
  {
    id: 7,
    title: "Apple Watch Series 9: Health Tracking Revolution",
    description: "The latest Apple Watch brings advanced health monitoring to your wrist. Is it worth the upgrade?",
    rating: 4.6,
    stars: 5,
    image: "https://images.unsplash.com/photo-1546868871-7041f2a55e12?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "Apple Watch Series 9",
    link: "/reviews/apple-watch-series-9",
    category: "Wearables",
    priceRange: "Premium"
  },
  {
    id: 8,
    title: "Fitbit Charge 5: The Ultimate Fitness Tracker",
    description: "Comprehensive fitness tracking meets sleek design. Our 3-month real-world testing review.",
    rating: 4.3,
    stars: 4,
    image: "https://images.unsplash.com/photo-1575311373937-040b8e1fd5b6?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "Fitbit Charge 5",
    link: "/reviews/fitbit-charge-5",
    category: "Wearables",
    priceRange: "Mid-Range"
  },
  {
    id: 9,
    title: "Peloton Bike+: Home Fitness Game Changer",
    description: "Is the premium price justified? We spent 6 months with the Peloton Bike+ to find out.",
    rating: 4.4,
    stars: 4,
    image: "https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "Peloton Bike+",
    link: "/reviews/peloton-bike-plus",
    category: "Fitness Equipment",
    priceRange: "Premium"
  },
  {
    id: 10,
    title: "Herman Miller Aeron: The Office Chair Gold Standard",
    description: "After years of use, we evaluate whether this expensive chair delivers on ergonomic promises.",
    rating: 4.7,
    stars: 5,
    image: "https://images.unsplash.com/photo-1586953208448-b95a79798f07?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "Herman Miller Aeron",
    link: "/reviews/herman-miller-aeron",
    category: "Office Equipment",
    priceRange: "Premium"
  },
  {
    id: 11,
    title: "WHOOP 4.0: 24/7 Health Monitoring",
    description: "The subscription-based fitness tracker promises insights into your recovery. Does it deliver?",
    rating: 4.1,
    stars: 4,
    image: "https://images.unsplash.com/photo-1611312449408-fcece27cdbb7?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "WHOOP 4.0",
    link: "/reviews/whoop-4-0",
    category: "Wearables",
    priceRange: "Premium"
  },
  {
    id: 12,
    title: "NordicTrack X22i: Premium Incline Treadmill",
    description: "Interactive training meets serious hardware. Our comprehensive review of this premium treadmill.",
    rating: 4.2,
    stars: 4,
    image: "https://images.unsplash.com/photo-1571902943202-507ec2618e8f?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
    alt: "NordicTrack X22i",
    link: "/reviews/nordictrack-x22i",
    category: "Fitness Equipment",
    priceRange: "Premium"
  }
];

export function ReviewsListPage() {
  usePageTitle(PAGE_TITLES.REVIEWS);
  
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [selectedPriceRange, setSelectedPriceRange] = useState('All');
  const [sortBy, setSortBy] = useState('rating');
  const reviewsPerPage = 6;

  // Get unique categories and price ranges
  const categories = ['All', ...Array.from(new Set(allReviews.map(review => review.category)))];
  const priceRanges = ['All', ...Array.from(new Set(allReviews.map(review => review.priceRange)))];

  // Filter and sort reviews
  const filteredReviews = useMemo(() => {
    const filtered = allReviews.filter(review => {
      const categoryMatch = selectedCategory === 'All' || review.category === selectedCategory;
      const priceMatch = selectedPriceRange === 'All' || review.priceRange === selectedPriceRange;
      return categoryMatch && priceMatch;
    });

    // Sort reviews
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'rating':
          return b.rating - a.rating;
        case 'title':
          return a.title.localeCompare(b.title);
        case 'newest':
          return b.id - a.id;
        default:
          return 0;
      }
    });

    return filtered;
  }, [selectedCategory, selectedPriceRange, sortBy]);

  // Calculate pagination based on filtered reviews
  const totalPages = Math.ceil(filteredReviews.length / reviewsPerPage);
  const currentReviews = useMemo(() => {
    const startIndex = (currentPage - 1) * reviewsPerPage;
    const endIndex = startIndex + reviewsPerPage;
    return filteredReviews.slice(startIndex, endIndex);
  }, [currentPage, filteredReviews]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleFilterChange = () => {
    setCurrentPage(1); // Reset to first page when filters change
  };

  const clearFilters = () => {
    setSelectedCategory('All');
    setSelectedPriceRange('All');
    setSortBy('rating');
    setCurrentPage(1);
  };

  const renderStars = (stars: number) => {
    return Array.from({ length: 5 }, (_, index) => (
      <Star 
        key={index} 
        size={16} 
        fill={index < stars ? "#f8961e" : "transparent"} 
        stroke={index < stars ? "#f8961e" : "#666"}
        strokeWidth={1}
      />
    ));
  };
  return <div className="w-full bg-[#0a2540] text-white">
      {/* Hero Section */}
      <section className="relative w-full h-[50vh] flex items-center">
        <div className="absolute inset-0 z-0">
          <div className="absolute inset-0 bg-gradient-to-b from-[#0a2540] via-transparent to-[#0a2540] opacity-90 z-10"></div>
          <ImageWithLoading 
            src="https://images.unsplash.com/photo-1586953208448-b95a79798f07?ixlib=rb-1.2.1&auto=format&fit=crop&w=2000&q=80" 
            alt="Modern workspace with health and wellness products" 
            className="w-full h-full" 
          />
        </div>
        <div className="container mx-auto px-4 md:px-8 relative z-10">
          <div className="max-w-4xl">
            <h1 className="text-4xl md:text-6xl font-extrabold leading-tight mb-6">
              PRODUCT REVIEWS
            </h1>
            <p className="text-xl md:text-2xl mb-8 text-gray-200 max-w-3xl">
              In-depth, honest reviews of the best health and wellness products
              on the market.
            </p>
          </div>
        </div>
      </section>
      {/* Reviews Grid */}
      <section className="py-16 px-4 md:px-8">
        <div className="container mx-auto">
          <div className="flex flex-col lg:flex-row gap-8">
            {/* Main Content - Reviews Grid */}
            <div className="flex-1">
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8 mb-12">
                {currentReviews.map((review) => (
                  <article key={review.id} className="bg-[#061a2c] rounded-lg overflow-hidden group hover:shadow-xl transition-all duration-300">
                    <div className="relative">
                      <ImageWithLoading 
                        src={review.image} 
                        alt={review.alt} 
                        className="w-full h-48 object-cover" 
                      />
                      <span className="absolute top-4 left-4 bg-[#06d6a0] text-[#0a2540] text-sm font-bold px-3 py-1 rounded">
                        REVIEW
                      </span>
                      <span className="absolute top-4 right-4 bg-[#0a2540] text-white text-xs px-2 py-1 rounded">
                        {review.category}
                      </span>
                    </div>
                    <div className="p-6 flex flex-col h-64">
                      <div className="flex items-center mb-3">
                        <div className="flex text-[#f8961e]">
                          {renderStars(review.stars)}
                        </div>
                        <span className="ml-2 text-sm font-medium">{review.rating}/5.0</span>
                      </div>
                      
                      {/* Title with fixed height and tooltip */}
                      <div className="relative mb-3">
                        <h3 
                          className="text-xl font-bold h-16 overflow-hidden leading-tight"
                          title={review.title}
                        >
                          <span className="line-clamp-2">
                            {review.title}
                          </span>
                        </h3>
                        {/* Tooltip for long titles */}
                        <div className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-black text-white text-sm rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-10 max-w-xs whitespace-normal">
                          {review.title}
                          <div className="absolute top-full left-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-black"></div>
                        </div>
                      </div>
                      
                      {/* Description with fixed height and tooltip */}
                      <div className="relative mb-4 flex-1">
                        <p 
                          className="text-gray-300 h-12 overflow-hidden leading-relaxed"
                          title={review.description}
                        >
                          <span className="line-clamp-2">
                            {review.description}
                          </span>
                        </p>
                        {/* Tooltip for long descriptions */}
                        <div className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-black text-white text-sm rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-10 max-w-sm whitespace-normal">
                          {review.description}
                          <div className="absolute top-full left-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-black"></div>
                        </div>
                      </div>
                      
                      <div className="flex items-center justify-between mt-auto">
                        <span className="text-sm text-[#06d6a0] font-medium">
                          {review.priceRange}
                        </span>
                        <a href={review.link} className="text-[#06d6a0] font-medium flex items-center hover:text-white transition-colors">
                          Read Review <ArrowRight size={16} className="ml-2" />
                        </a>
                      </div>
                    </div>
                  </article>
                ))}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex justify-center items-center space-x-2">
                  <button
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                    className={`p-2 rounded-lg transition-colors ${
                      currentPage === 1 
                        ? 'bg-gray-700 text-gray-500 cursor-not-allowed' 
                        : 'bg-[#061a2c] text-white hover:bg-[#06d6a0] hover:text-[#0a2540]'
                    }`}
                  >
                    <ChevronLeft size={20} />
                  </button>
                  
                  {Array.from({ length: totalPages }, (_, index) => {
                    const page = index + 1;
                    return (
                      <button
                        key={page}
                        onClick={() => handlePageChange(page)}
                        className={`px-4 py-2 rounded-lg transition-colors font-medium ${
                          currentPage === page
                            ? 'bg-[#06d6a0] text-[#0a2540]'
                            : 'bg-[#061a2c] text-white hover:bg-[#06d6a0] hover:text-[#0a2540]'
                        }`}
                      >
                        {page}
                      </button>
                    );
                  })}
                  
                  <button
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className={`p-2 rounded-lg transition-colors ${
                      currentPage === totalPages 
                        ? 'bg-gray-700 text-gray-500 cursor-not-allowed' 
                        : 'bg-[#061a2c] text-white hover:bg-[#06d6a0] hover:text-[#0a2540]'
                    }`}
                  >
                    <ChevronRight size={20} />
                  </button>
                </div>
              )}
            </div>

            {/* Sidebar - Filters */}
            <div className="lg:w-80">
              <div className="bg-[#061a2c] rounded-lg p-6 sticky top-8">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-lg font-bold flex items-center">
                    <Filter size={20} className="mr-2" />
                    Filters
                  </h3>
                  <button
                    onClick={clearFilters}
                    className="text-sm text-[#06d6a0] hover:text-white transition-colors flex items-center"
                  >
                    <X size={16} className="mr-1" />
                    Clear All
                  </button>
                </div>

                {/* Sort By */}
                <div className="mb-6">
                  <label className="block text-sm font-medium mb-3">Sort By</label>
                  <select
                    value={sortBy}
                    onChange={(e) => {
                      setSortBy(e.target.value);
                      handleFilterChange();
                    }}
                    className="w-full bg-[#0a2540] text-white border border-gray-600 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#06d6a0]"
                  >
                    <option value="rating">Highest Rating</option>
                    <option value="title">Alphabetical</option>
                    <option value="newest">Newest First</option>
                  </select>
                </div>

                {/* Category Filter */}
                <div className="mb-6">
                  <label className="block text-sm font-medium mb-3">Category</label>
                  <div className="space-y-2">
                    {categories.map((category) => (
                      <label key={category} className="flex items-center cursor-pointer">
                        <input
                          type="radio"
                          name="category"
                          value={category}
                          checked={selectedCategory === category}
                          onChange={(e) => {
                            setSelectedCategory(e.target.value);
                            handleFilterChange();
                          }}
                          className="sr-only"
                        />
                        <div className={`w-4 h-4 rounded-full border-2 mr-3 flex items-center justify-center ${
                          selectedCategory === category 
                            ? 'border-[#06d6a0] bg-[#06d6a0]' 
                            : 'border-gray-400'
                        }`}>
                          {selectedCategory === category && (
                            <div className="w-2 h-2 rounded-full bg-[#0a2540]"></div>
                          )}
                        </div>
                        <span className={`text-sm ${
                          selectedCategory === category ? 'text-[#06d6a0]' : 'text-gray-300'
                        }`}>
                          {category}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>

                {/* Price Range Filter */}
                <div className="mb-6">
                  <label className="block text-sm font-medium mb-3">Price Range</label>
                  <div className="space-y-2">
                    {priceRanges.map((priceRange) => (
                      <label key={priceRange} className="flex items-center cursor-pointer">
                        <input
                          type="radio"
                          name="priceRange"
                          value={priceRange}
                          checked={selectedPriceRange === priceRange}
                          onChange={(e) => {
                            setSelectedPriceRange(e.target.value);
                            handleFilterChange();
                          }}
                          className="sr-only"
                        />
                        <div className={`w-4 h-4 rounded-full border-2 mr-3 flex items-center justify-center ${
                          selectedPriceRange === priceRange 
                            ? 'border-[#06d6a0] bg-[#06d6a0]' 
                            : 'border-gray-400'
                        }`}>
                          {selectedPriceRange === priceRange && (
                            <div className="w-2 h-2 rounded-full bg-[#0a2540]"></div>
                          )}
                        </div>
                        <span className={`text-sm ${
                          selectedPriceRange === priceRange ? 'text-[#06d6a0]' : 'text-gray-300'
                        }`}>
                          {priceRange}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>

                {/* Results Count */}
                <div className="pt-4 border-t border-gray-600">
                  <p className="text-sm text-gray-400">
                    Showing {currentReviews.length} of {filteredReviews.length} reviews
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>;
}